from rest_framework import serializers
from .models import Author, Post


class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = ["id", "name", "email"]


class PostSerializer(serializers.ModelSerializer):
    author = AuthorSerializer()  # 嵌套 AuthorSerializer

    class Meta:
        model = Post
        fields = ["id", "author", "title", "text", "created_date", "published_date"]

    def create(self, validated_data):
        author_data = validated_data.pop("author")
        email = author_data.get("email")
        name = author_data.get("name")
        author = Author.objects.filter(name=name, email=email).first()
        if author is None:
            author = Author.objects.create(**author_data)
            print("Created new author:", author)
        return Post.objects.create(author=author, **validated_data)
